import axios from "axios";
import {
  randomFill
} from "crypto";
import { deepCopyObj } from "@/assets/js/help.js";
import api from "../../../fetch/api";
import { debuglog } from "util";

export default {
  data() {
    let validateTel = (rule, value, callback) => {
      // validRequired(rule, value, callback);
      if (!/^1\d{10}$/.test(value)) {
        callback(new Error('请输入正确的电话号码'));
      } else {
        callback();
      }
    };
    let validateParkList = (rule, value, callback) => {
      // validRequired(rule, value, callback);
      if (value.length == 0) {
        callback(new Error('请选择停车场'));
      } else {
        callback();
      }
    };
    let validatePassword = (rule, value, callback) => {
      // validRequired(rule, value, callback);
      if (!(/^([a-zA-Z0-9]|[._]){5,19}$/.test(value))) {
        callback(new Error('请输入6-20位不包含特殊字符的密码'));
      } else {
        callback();
      }
    };
    return {
      editIndex: "",
      privilegeTree: [],
      privilegeTreeShow: [],
      parkListNameArr:[],
      seatPrivilegeData: {
        modalName: "绑定权限",
        id: "",
        type: "",
      },
      seatForm: {
        des: "",
        id: "",
        password: "",
        userid: "",
        username: "",
        userphone: "",
        operatorId: "",
        speaker: false,
        parkList: [],
      },
      seatFormRules: {
        userid: [{
            required: true,
            message: '请输入账号',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 30,
            message: '长度在 2 到 30 个字符',
            trigger: 'change'
          }
        ],
        username: [{
            required: true,
            message: '请输入坐席姓名',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 30,
            message: '长度在 2 到 30 个字符',
            trigger: 'change'
          }
        ],
        userphone: [{
          required: true,
          validator: validateTel,
          trigger: 'blur'
        }],
        parkList: [{
          required: true,
          validator: validateParkList,
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }, {
          required: true,
          validator: validatePassword,
          trigger: 'blur'
        }]
      },
    }
  },
  created() {
    this.getPrivilegeTree();
  },
  computed: {
    inputParkstr: function () {
      var parkListArr = []
      var parkNameList = []
      if(this.seatForm.parkList.length!=0){
        parkListArr = this.seatForm.parkList
        parkListArr.forEach(parkListEle => {
          parkNameList.push(parkListEle.name)
        })
        // console.log(parkNameList)
      }
      return parkNameList.join("/")
    }
  },
  methods: {
    getList() {
      this.getSeatList(this.searchParams);
    },
    // 查询列表
    getSeatList(aparams) {
      let self = this,
        params = {
          operatorId: window.sessionStorage.getItem("_operatorID"),
          pageNumber: this.pageNumber,
          pageSize: this.pageSize
        };
      params = $.extend({}, params, aparams);
      axios.post("cenduty/seat/list", params).then(res => {
        let mainDate = res.data.data
        let list = mainDate.list;
        self.tbodysInfo = list ? list : [];
        self.total = mainDate.total;
      }).catch((error) => {
        console.log(error)
      })
    },
    forceoffwork(rowData){
      let self = this
      this.showDialog("确认将该收费员强制下班?",[],function(){
        axios.post('cenduty/seat/force_off_duty?id='+rowData.id).then(res=>{
          console.log('强制下班结果',res)
          if (res.data.status == 1) {
            self.showToast("操作成功", 1);
            self.getList();
          } else {
            self.showToast("操作失败", 2);
          }
        }).catch((error) => {
          console.log(error)
        })
      },"温馨提示", function () {

      })
    },
    handle(rowData, type) {
      let _this = this;
      _this.seatPrivilegeData.id = rowData.id;
      switch (type) {
        case 'edit':
          this._addSeat(rowData);
          break;
        case 'isUp':
          this.isUpModal(rowData);
          break;
        case 'del':
          this._del(rowData.id);
          break;
        default:
          break;
      }
    },
    // 打开新增
    _addSeat(rowData) {
      this.emptyData();
      this.seatPrivilegeData.modalName = "绑定权限";
      this.seatPrivilegeData.type = "add";

      this.privilegeTreeShow = JSON.parse(JSON.stringify(this.privilegeTree).replace(/channelName/g, "name"));
      if (rowData) {
        this.setEditData(rowData);
        this.getBindParkList();
        this.seatPrivilegeData.type = "edit";
      }
      this.toOpenModal('seatFormModal', 1);
    },
    emptyData() {
      this.seatForm = {
        des: "",
        // id: "",
        password: "",
        userid: "",
        username: "",
        userphone: "",
        speaker: false,
        operatorId: window.sessionStorage.getItem("_operatorID"),
        parkList: [],
      }
    },
    setEditData(rowData) {
      this.seatForm = {
        id: rowData.id,
        password: "",
        operatorId: window.sessionStorage.getItem("_operatorID"),
        des: rowData.des,
        userid: rowData.userid,
        username: rowData.username,
        userphone: rowData.userphone,
        speaker: rowData.speaker==1 ? true : false,
        parkList: [],
      }
    },
    // 保存坐席信息
    saveSeatForm() {
      let _this = this;
      _this.$refs['seatForm'].validate((valid) => {
        if (valid) {
          let params = deepCopyObj(this.seatForm)
          params.speaker = params.speaker ? 1 : 0
          let userInfoJson = window.sessionStorage.getItem("userInfo")
          let userInfoObj = JSON.parse(userInfoJson)
          if (this.seatPrivilegeData.type == 'add') {
            params.createBy = userInfoObj.nickname
            axios.post("cenduty/seat/add", params)
              .then(res => {
                _this.getList();
                _this.closed('seatFormModal', 1)
                _this.showToast("操作成功", 1)
              })
              .catch((error) => {
                console.log(error)
              })
          } else {
            params.updateBy = userInfoObj.nickname
            axios.post("cenduty/seat/update", params)
              .then(res => {
                console.log(res)
                _this.getList();
                _this.closed('seatFormModal', 1)
                _this.showToast("操作成功", 1)
              })
              .catch((error) => {
                console.log(error)
              })
          }
        }
      })
    },
    // 获取列表树
    getPrivilegeTree() { 
      let _this = this;
      let params = {
        operatorId: window.sessionStorage.getItem("_operatorID"),
      }
      axios.get("cenduty/seat/getOperatorParkList", {
          params: params
        })
        .then(res => {
          console.log('OperatorPark',res)
          let mainData = res.data.data
          _this.privilegeTree = mainData ? JSON.parse(JSON.stringify(mainData)) : [];
          _this.privilegeTreeShow = mainData ? JSON.parse(JSON.stringify(mainData).replace(/channelName/g, "name")) : [];
        })
        .catch((error) => {
          console.log(error)
        })
    },
    lookPrivilege(id) {
      let _this = this;
      _this.seatPrivilegeData.id = id
      _this.seatPrivilegeData.modalName = "查看权限";
      _this.privilegeTreeShow = JSON.parse(JSON.stringify(_this.privilegeTree).replace(/channelName/g, "name"));
      _this.getBindParkList().then(function () {
        _this.openPrivilegeModal();
      }).catch(function (err) {
        console.log(err);
      });
    },
    // 获取权限的的列表
    getBindParkList() {
      let _this = this;
      return new Promise(function (resolve, reject) {
        let params = {
          id: _this.seatPrivilegeData.id
        }
        let type = _this.seatPrivilegeData.modalName.indexOf("查看权限") > -1 ? true : false;
        axios.get("cenduty/seat/getBindParkList", {
            params: params
          })
          .then(res => {
            console.log(res)
            //获取选中的通道id  放到数组里面
            let channeIdlList = [];
            let mainData = res.data.data
            _this.seatForm.parkList = mainData;

            if (mainData && mainData.length > 0) {
              mainData.forEach(element => {
                if (element.channelList && element.channelList.length > 0) {
                  element.channelList.forEach(subElement => {
                    channeIdlList.push(subElement.id)
                  })
                }
              })
            }
            _this.privilegeTreeShow.forEach(element => {
              //父节点无选项框
              // element.nocheck = true;
              //查看时不允许更改权限
              if (type) {
                element.chkDisabled = true;
              }
              if (element.channelList && element.channelList.length > 0) {
                element.channelList.forEach(subElement => {
                  //查看时不允许更改权限
                  if (type) {
                    subElement.chkDisabled = true;
                  }
                  // 默认选中节点框
                  if (channeIdlList.indexOf(subElement.id) > -1) {
                    console.log(channeIdlList, subElement.id, channeIdlList.indexOf(subElement.id) > -1)
                    subElement.checked = true;
                  }
                })
              }
            })
            resolve();
          })
          .catch((error) => {
            console.log(error)
            reject()
          })
      });
    },
    openPrivilegeModal() {
      let _this = this;
      let settings = {
        check: {
          enable: true,
          chkStyle: "checkbox",
        },
        data: {
          key: {
            children: "channelList"
          },
          simpleData: {
            enable: false
          }
        },
        view: {
          showIcon: false,
          showLine: false,
        }
      };
      _this.toOpenModal('setPrivilegeModal', 2);

      setTimeout(function () {
        let treeObj = $.fn.zTree.init($("#privilegeTree"), settings, _this.privilegeTreeShow);
        treeObj.expandAll(true);
      }, 0)
    },
    //选择权限点击确定时调用
    SetPrivilege(treeId) {
      let self = this
      let tree = $.fn.zTree.getZTreeObj(treeId);
      let nodes = tree.getCheckedNodes(true);
      let parkList = JSON.parse(JSON.stringify(this.privilegeTree))
      parkList.forEach((element, index) => {
        element.channelList = []
      })
      var ids = []
      nodes.forEach((element, index) => {
        ids.push(element.id)
        if (!element.channelList) {
          let parentsParkId = element.getParentNode().parkId;
          element = JSON.parse(JSON.stringify(element).replace(/name/g, 'channelName'));
          parkList.forEach(parkListElement => {
            if (parentsParkId == parkListElement.parkId) {
              parkListElement.channelList.push(element)
            }
          })
        }
      });
      nodes.forEach((element,index)=>{
        self.privilegeTreeShow.forEach(item=>{
          if(item.checked && ids.indexOf(item.id)==-1){
            delete item.checked
            if(element.channelList){
              item.channelList.forEach(pitem=>{
                if(pitem.checked){
                  delete pitem.checked
                }
              })
            }
          }
          if(element.channelList){
            if(element.id==item.id){
              item.checked = true
              item.channelList.forEach(pitem=>{
                if(pitem.checked){
                  delete pitem.checked
                }
                if(ids.indexOf(pitem.id)>-1){
                  pitem.checked = true
                }
              })
            }
          }
        })
      })
      this.seatForm.parkList = [];
      parkList.forEach(parkListEle => {
        if (parkListEle.channelList.length > 0) {
          this.seatForm.parkList.push(parkListEle)
          this.parkListNameArr.push(parkListEle.name)
        }
      })
      // console.log(this.parkListNameArr)
      this.closed('setPrivilegeModal', 2)
    },
    isUpModal(index) {
      let _this = this;
      _this.editIndex = index;
      _this.toOpenModal('freezeModal');
    },
    // 启用或冻结坐席信息
    _isUp(rowData) {
      let self = this;
      if (rowData.seatStatus == 0) {
        axios.post("cenduty/seat/lock?id=" + rowData.id).then(res => {
          console.log('冻结结果',res)
          if (res.data.status == 1) {
            self.showToast("冻结成功", 1);
            this.closed('freezeModal')
            self.getList();
          } else {
            self.showToast("冻结失败", 2);
          }
        }).catch((error) => {
          console.log(error)
        })
      } else {
        axios.post("cenduty/seat/start?id=" + rowData.id).then(res => {
          console.log('启用结果',res)
          if (res.data.status == 1) {
            self.showToast("启用成功", 1);
            this.closed('freezeModal')
            self.getList();
          } else {
            self.showToast("启用失败", 2);
          }
        }).catch((error) => {
          console.log(error)
        })
      }
    },
    // 删除坐席信息
    _del(id) {
      let self = this;
      this.showDialog("是否确认删除所选记录？", [], function () {
        axios.post("cenduty/seat/delete?id=" + id).then(res => {
          if (res.data.status == 1) {
            self.showToast("删除成功", 1);
            self.getList();
          } else {
            self.showToast("删除失败", 2);
          }
        }).catch((error) => {
          console.log(error)
        })
      }, "温馨提示", function () {

      });
    },
    // 必须定义获取多列的方法
    filterMultiCheck(selectionArr) {
      let result = [];
      selectionArr.map((item) => {
        result.push(item.id);
      });
      return result;
    }
  },
  filters: {
    timeStampFormat: function(value){
      if(!value){
        return '';
      }
      return moment(value).format('YYYY-MM-DD HH:mm:ss')
    }
  },
    onlineStatusText: function (value) {
      switch (value) {
          case 0:
              return "休息中"
              break;
          case 1:
              return "上班中"
              break;
          default:
              break;
      }
  }
}
